﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using UcAsp.Net.IDAL;
using UcAsp.Net.Interface;
using UcAsp.Net.Model;
using Clear = UcAsp.Net.BLL.ClearCodeBLL;
namespace UcAsp.Net.BLL
{
    public class ArticlesBLL
    {
        private static readonly IArticlesDAL dal = DALFactory.DataAccess.CreateArticles();
        private static readonly ISetFiledDAL dalfiled = DALFactory.DataAccess.CreateSetFiled();
        private static readonly IArticlesPageDAL dalpage = DALFactory.DataAccess.CreateArticlesPage();
        private static readonly ICache cache = DALFactory.CacheAccess.CreateCache();

        private QrCodeBLL qr = new QrCodeBLL();
        public List<Articles> Select(int? categoriesid, bool isrecommend, bool isrelease, string keyword, int pagesize, int pageindex, out int pagecount)
        {
            return dal.Select(null, categoriesid, isrecommend, isrelease, null, null, keyword, pagesize, pageindex, out pagecount);
        }
        public List<Articles> Select(int userid, int? categoriesid, bool isrecommend, bool isrelease, string keyword, int pagesize, int pageindex, out int pagecount)
        {
            return dal.Select(userid, categoriesid, isrecommend, isrelease, null, null, keyword, pagesize, pageindex, out pagecount);
        }
        public List<Articles> Select(int userid, int? categoriesid, bool isrecommend, bool isrelease, DateTime begin, DateTime end, string keyword, int pagesize, int pageindex, out int pagecount)
        {
            return dal.Select(userid, categoriesid, isrecommend, isrelease, begin, end, keyword, pagesize, pageindex, out pagecount);
        }
        public List<ArticelsViews> SelectViews(int? categoriesid, bool? isrecommend, bool? isrelease, DateTime? begin, DateTime? end, string keyword, int pagesize, int pageindex, out int pagecount)
        {
            return dal.SelectViews(null, categoriesid, isrecommend, isrelease, begin, end, keyword, pagesize, pageindex, out pagecount);
        }
        public List<ArticelsViews> SelectViews(int? userid, int? categoriesid, bool? isrecommend, bool? isrelease, DateTime? begin, DateTime? end, string keyword, int pagesize, int pageindex, out int pagecount)
        {
            return dal.SelectViews(userid, categoriesid, isrecommend, isrelease, begin, end, keyword, pagesize, pageindex, out pagecount);
        }
        public List<ArticelsViews> SelectViews(int? userid, int? categoriesid, int pagesize, int pageindex, out int pagecount)
        {
            return SelectViews(userid, categoriesid, null, null, null, null, null, pagesize, pageindex, out pagecount);
        }
        public List<Articles> Search(int categoriesid, string keyword, int pagesize, int pageindex, out int pagecount)
        {
            return dal.Select(null, categoriesid, false, true, DateTime.Now, DateTime.Now, keyword, pagesize, pageindex, out pagecount);
        }

        public string ArticesView(int categoriesid, out string jstxt, Articles model,out string image)
        {
            List<SetFiled> list = dalfiled.Select(categoriesid);
            StringBuilder str = new StringBuilder();
            StringBuilder js = new StringBuilder();
            str.AppendFormat("<input name=\"ID\" type=\"hidden\" value=\"{0}\" />\r\n", model.ID);
            js.AppendFormat("ID: $(\"input[name='ID']\").val()");
            str.AppendFormat("<input name=\"IsRelease\" type=\"hidden\" value=\"{0}\" />\r\n", model.IsRelease);
            js.AppendFormat(",IsRelease: $(\"input[name='IsRelease']\").val()");
            str.AppendFormat("<input name=\"IsRecommend\" type=\"hidden\" value=\"{0}\" />\r\n", model.IsRecommend);
            js.AppendFormat(",IsRecommend: $(\"input[name='IsRecommend']\").val()");
            image = string.Empty;
            foreach (SetFiled setfiled in list)
            {
                switch (setfiled.InputType.ToLower())
                {
                    case "text":
                        str.AppendFormat("<div class=\"control-group\"><label class=\"control-label\">{0}</label><div class=\"controls\"><input class=\"text-input large-input\" type=\"text\" id=\"{1}\" name=\"{1}\" value=\"{2}\" /></div></div>\r\n", setfiled.CnName, setfiled.FiledName, GetValue(model, setfiled.FiledName));
                        js.AppendFormat(",{0}: $(\"input[name='{0}']\").val()", setfiled.FiledName);
                        break;

                    case "hidden":
                        str.AppendFormat("<input name=\"{0}\" type=\"hidden\" value=\"{1}\" />\r\n", setfiled.FiledName, setfiled.DefaultValue);
                        js.AppendFormat(",{0}: $(\"input[name='{0}']\").val()", setfiled.FiledName);
                        break;

                    case "textarea":
                        str.AppendFormat("<div class=\"control-group\"><label class=\"control-label\">{0}</label><div class=\"controls\"><textarea id=\"{1}\" name=\"{1}\" cols=\"20\" rows=\"2\">{2}</textarea></div></div>\r\n", setfiled.CnName, setfiled.FiledName, GetValue(model, setfiled.FiledName));
                        js.AppendFormat(",{0}: tinyMCE.get(\"{0}\").getContent()", setfiled.FiledName);
                        break;

                    case "select":
                        string[] rellection = setfiled.StoreText.Split(',');
                        Assembly obj = Assembly.LoadFrom(System.Web.HttpContext.Current.Server.MapPath("/") + @"\bin\UcAsp.Net.BLL.dll");
                        Type type = obj.GetType(rellection[0]);

                        str.AppendFormat("<div class=\"control-group\"><label class=\"control-label\">{0}</label><div class=\"controls\"><select name=\"{1}\">\r\n", setfiled.CnName, setfiled.FiledName);

                        Object o = Activator.CreateInstance(type);
                        List<object> listselect = ((ISelect)o).Execute(setfiled.Sort);

                        foreach (Select s in listselect)
                        {
                            string value = GetValue(model, setfiled.FiledName);
                            if (s.Value.Equals(GetValue(model, setfiled.FiledName)) || s.Value.Equals(categoriesid.ToString()))
                            {
                                str.AppendFormat("<option value=\"{0}\" selected>{1}</option>\r\n", s.Value, s.Name);
                            }
                            else
                            {
                                str.AppendFormat("<option value=\"{0}\" >{1}</option>\r\n", s.Value, s.Name);
                            }
                        }
                        str.AppendFormat("</select></div></div>\r\n");
                        js.AppendFormat(",{0}: $(\"select[name='{0}']\").val()", setfiled.FiledName);
                        break;

                    case "image":
                        str.AppendFormat("<div class=\"control-group\"><label  class=\"control-label\">{0}</label><div class=\"controls\"><input class=\"input-small\" type=\"text\" id=\"File{1}\" name=\"File{1}\" value=\"{2}\"  />\r\n<input id=\"{1}\" name=\"{1}\" type=\"file\"></div></div>\r\n", setfiled.CnName, setfiled.FiledName, GetValue(model, setfiled.FiledName));
                        if (image == string.Empty)
                        {
                            image = "'"+setfiled.FiledName+"'";
                        }
                        else
                        {
                            image = image + "," + "'" + setfiled.FiledName + "'";
                        }
                        js.AppendFormat(",{0}: $(\"input[name='File{0}']\").val()", setfiled.FiledName);
                        break;
                }
            }
            jstxt = js.ToString();
            return str.ToString();
        }

        public static List<ArticelsViews> GetSubject(int id,string theme)
        {
           
             Subjects subject = SubjectsConfig.GetSubjects(id,theme);
             return new ArticlesBLL().Subject(subject.Categories, subject.Keywords, int.Parse(subject.MaxNum), int.Parse(subject.WhoView));
        }
        public static List<ArticelsViews> GetSubject(int id, int cid, string theme)
        {
            Subjects subject = SubjectsConfig.GetSubjects(id, cid, theme);
            List<ArticelsViews> list = new ArticlesBLL().Subject(subject.Categories, subject.Keywords, int.Parse(subject.MaxNum), int.Parse(subject.WhoView));
            return list;
        }
        public static List<ArticelsViews> GetMessageSubject(int id, int cid,string theme)
        {
            Subjects subject = SubjectsConfig.GetMessageSubjects(id, cid,theme);
            return new ArticlesBLL().Subject(subject.Categories, subject.Keywords, int.Parse(subject.MaxNum), int.Parse(subject.WhoView));
        }
        private List<ArticelsViews> Subject(string categoriesid, string keyword, int maxnum, int whoview)
        {
            if (cache.GetCache("Subject" + categoriesid) == null)
            {
                cache.CreateCache(dal.Subject(categoriesid, keyword, maxnum, whoview), "Subject" + categoriesid);
            }
            return (List<ArticelsViews>)cache.GetCache("Subject" + categoriesid);
        }
        public Articles GetArticles(int id)
        {
            Articles views = dal.Limt(id);
           // qr.GetQrImagePath(views.ID.ToString());
            return views;
        }
        public ArticelsViews GetArtieByShowPath(string showpath, out int count, out List<ArticelsViews> nextorprev)
        {
            ArticelsViews views=dal.GetArtieByShowPath(showpath, out count, out nextorprev);
          //  qr.GetQrImagePath(views.ID.ToString());
            return views;
        }
        public ArticelsViews GetArtieById(int id, out int count, out List<ArticelsViews> nextorprev)
        {
            ArticelsViews views= dal.GetArtieById(id, out count, out nextorprev);
           // qr.GetQrImagePath(views.ID.ToString());
            return views;
        }
        private string GetValue(Articles article, string text)
        {
            Type type = article.GetType();
            System.Reflection.PropertyInfo p = type.GetProperty(text);
            if (article.ID != 0)
            {
                if (p.GetValue(article, null) != null)
                {
                    string value = p.GetValue(article, null).ToString();
                    return value;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
        public Articles Insert(Articles model)
        {
            cache.RemoveAllCache();
            model.ArticleContent = Clear.ClearCode(model.ArticleContent);
            return dal.Insert(model);
        }
        public bool Update(Articles model)
        {
            cache.RemoveAllCache();
            model.ArticleContent = Clear.ClearCode(model.ArticleContent);
            return dal.Update(model);
        }
        public Articles GetArtieByTitle(string title)
        {
            return dal.GetArtieByTitle(title);
        }

        public bool Delete(int id)
        {
            Articles model = GetArticles(id);
            dalpage.Delete(id);
            cache.RemoveAllCache();
            return dal.Delete(model);
        }
        public bool Delete(DateTime Time, int CategoriesID)
        {
            cache.RemoveAllCache();
            return dal.Delete(Time, CategoriesID);
        }
        public Articles RecommdRecord(int id, bool recommd)
        {
            return dal.RecommdRecord(id, recommd);
        }
        public Articles ReleaseRecord(int id, bool release)
        {
            return dal.ReleaseRecord(id, release);
        }
    }
}